(function($) {

	$(function() {

		js_select_dropdown();
		js_sections_group();
		js_featured_slider();
		js_pinterest();

		// trim user name
		$('#profile-button span').dotdotdot({
			tolerance: 1
		});

		// trim product name
		$('.product .name, .product, .trim-text').dotdotdot({
			tolerance: 1
		});
		
		// product bar
		$('.product-bar').each(function() {
			var jelm = $(this), jtarget = $('#'+jelm.attr('rel'));
			var target_t = jtarget.offset().top, target_h = jtarget.height();
			if($(this).hasClass('search-bar'))
			{
				//Check if this is mobile
				if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile Safari/i.test(navigator.userAgent))
				{
				 	if($(window).width()>750) return;
				}
				else
				{
					return;
				}
			}
			$(window).scroll(function() {
				
				if ( $(window).scrollTop() > target_t + target_h - 40 ) {
					jelm.fadeIn(300);
				} else {
					jelm.fadeOut(100);
				}
				
			});
		});

		// categories toggle
		$('ul.categories').each(function() {
			var jelm = $(this);
			jelm.find('.has-children > .arrow').bind('click', function() {
				$(this).parent().find('> .sub-categories').slideToggle(100);
			});
		});

		// Equalize Height
		$('.featured-comments .comment-block').equalizeHeights();

		// scrollTo Elm
		$('.scrollTo').bind('click', function() {
			$.scrollToElm( $($(this).attr('href')) );
		});
		
		$('.ajax-load').bind('appear', function() {
			$(this).trigger('click');
		});
		
		
	});
	
	$(window).load(function() {
		// only for ipad and desktop
//		if ( $(window).width() >= 480 ) {
			js_items_slider();
			js_banner_rotator();
//		}
	});

	$.fn.equalizeHeights = function() {
		return this.height(Math.max.apply(this, $(this).map(function(i,e){
			return $(e).height();
		}).get()));
    }
	
	$.extend( $.easing, {
		customEasing: function (x, t, b, c, d) {
			return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
		},
		customEasing2: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
		},
		customEasing3: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*(t/=d)*t*((s+1)*t - s) + b;
		}
	});
	
	function js_featured_slider() {
		$('.featured-slider').each(function() {
			var elm = this, jelm = $(elm);

			if ( jelm.find('> *').length <= 1 ) return ;

			jelm.find('> *').wrapAll('<div class="featured-slider-inner" />');
			
			var btn_prev = $('<a class="btn-prev">'+lang.previous+'</a>');
			var btn_next = $('<a class="btn-next">'+lang.next+'</a>');
			jelm.append(btn_prev).append(btn_next);
			
			var jpager = $('<div class="featured-slider-nav" />');
			jelm.append(jpager);
			
			// responsive
			if ( $(window).width() <= 480 ) {
				jelm.find('.products-row').each(function() {
					$(this).find('.product:gt(1)').addClass('hidden');
					$(this).removeClass('products-grid-6');
					$(this).addClass('products-grid-2');
				});
			} else if ( $(window).width() <= 640 ) {
				jelm.find('.products-row').each(function() {
					$(this).find('.product:gt(3)').addClass('hidden');
					$(this).removeClass('products-grid-6');
					$(this).addClass('products-grid-4');
				});
			}
			
			jelm.find('.featured-slider-inner').cycle({
				slides: '> *',
				fx: 'scrollHorz',
				speed: 500,
				easing: 'customEasing',
				timeout: 0,
				next: btn_next,
				prev: btn_prev,
				cleartypeNoBg: true,
				nowrap: 1,
				pager: jpager,
				slideActiveClass: 'activeSlide',
				pagerTemplate: '<a><span>{{title}}</span></a>',
				allowWrap : false,
				log: false,
				swipe: true
			}).on('cycle-update-view', function(event, opts) {
				var index = opts.currSlide;
				btn_prev.css('opacity', index == 0 ? .3 : 1);
				btn_next.css('opacity', index == opts.slideCount - 1 ? .3 : 1);
			});
		});
	}
	function var_dump(obj)
	{
		var out='';
		for(var i in obj){out+=i+": "+obj[i]+"\n";}
		alert(out);
	}
	function js_select_dropdown() {
		$(document).on('click', '.wrapper-dropdown', function() {
			$(this).toggleClass('active');
		});
		
		$(document).on('click', '.div-wrapper-dropdown > .button', function() {
			$('.div-wrapper-dropdown.active').not($(this).parent('.div-wrapper-dropdown')).toggleClass('active');
			$(this).parent('.div-wrapper-dropdown').toggleClass('active');
			return false;
		});
		
		$(document).on('click', function(e) {
			if ( $(e.target).closest('.div-wrapper-dropdown').length == 0 )
				$('.div-wrapper-dropdown.active').toggleClass('active');
		});
	}
	
	function js_banner_rotator() {
		$('.banners-rotator').each(function() {
			var elm = this, jelm = $(elm);
			jelm.append('<div class="banners-rotator-nav" />');

			var jpager = jelm.find('.banners-rotator-nav');
			var jelms = jelm.find('.ad-container').addClass('banners-rotator-items');
			jelms.cycle({
				slides: '> *',
				fx: 'scrollHorz',
				pause: 1,
				timeout: 6000,
				speed: 500,
				delay: 1000,
				fit: true,
				width: '100%',
				pager: jpager,
				pagerTemplate: '<a><span>{{title}}</span></a>',
				allowWrap : false,
				log: false,
				swipe: true
			});
		});
	}
	
	function js_items_slider() {
		$('.items-slider').each(function() {
			var elm = this, jelm = $(elm);

			if ( jelm.attr('processed') == 'yes' ) return ;
			if ( jelm.find('> *').length <= 1 ) return ;
			
			jelm.find('> *').wrapAll('<div class="items-slider-inner" />');

			var btn_prev = $('<a class="btn-prev">'+lang.previous+'</a>');
			var btn_next = $('<a class="btn-next">'+lang.next+'</a>');
			jelm.append(btn_prev).append(btn_next);
			jelm.find('.items-slider-inner').cycle({
				slides: '> *',
				fx: 'scrollHorz',
				speed: 500,
				easing: 'customEasing',
				timeout: 0,
				next: btn_next,
				prev: btn_prev,
				cleartypeNoBg: true,
				allowWrap : false,
				log: false,
				swipe: true
			}).on('cycle-update-view', function(event, opts) {
				var index = opts.currSlide;
				btn_prev.css('opacity', index == 0 ? .3 : 1);
				btn_next.css('opacity', index == opts.slideCount - 1 ? .3 : 1);
			});;

			// mark as process
			jelm.attr('processed', 'yes');
		});
	}
	
	function js_sections_group() {
		$('.sections-group').each(function() {
			var jelm = $(this), jtitles = $('<ul class="sections-nav" />');
			
			jelm.find('> section').each(function() {
				var title = $(this).find('h2.component-title').html(), id = $(this).find('h2.component-title').attr('id');
				title = $(this).find('h2.component-title').attr('title') || title;

				jtitles.append('<li><a href="#'+id+'">'+title+'</a></li>');
			});
			
			jtitles.prependTo(jelm);
			jtitles.navScrolling({
				offset: -60
			});
		});
	}
	
	var js_pinterest = $.js_pinterest = function () {
		$('.pinterest').each(function() {
			var jelm = $(this);
			console.log('loaded');
			jelm.imagesLoaded(function() {
				var handler = jelm.find('> .product');
				var options = {
					itemWidth: 230, // Optional min width of a grid item
					autoResize: true, // This will auto-update the layout when the browser window is resized.
					container: jelm, // Optional, used for some extra CSS styling
					offset: 26, // Optional, the distance between grid items
					outerOffset: 13, // Optional the distance from grid to parent
					flexibleWidth: '50%' // Optional, the maximum width of a grid item
				};
				handler.wookmark(options);
			});
		});
	}
	
	$.fn.navScrolling = function(options) {
		options = $.extend({}, {
			offset: 0
		}, options)
		
		return this.each(function() {
			$(this).find('a').bind('click.tabs', function() {
				if ( $(this).attr('href').charAt(0) == '#' && $($(this).attr('href')).length > 0 ) {
					var targetOffset = $($(this).attr('href')).offset().top;
					$('html, body').animate({scrollTop: targetOffset + options.offset}, 1000, 'customEasing');

					return false;
				}
			});
		});
	}
	
})(jQuery);

$(document).ready(function(){
	$("#nav-menu li").hover(function()
	{
		$(this).addClass("activer");
		$(this).find("ul:first").show(200);
		$(this).closest('li').addClass("activer");
	},
	function()
	{
		$(this).closest('li').removeClass("activer");
		$(this).removeClass("activer");
		$(this).find("ul:first").hide()
	})
});

/* DropDown */
function DropDown(el) {
	this.dd = el;
	this.placeholder = this.dd.children('span');
	this.opts = this.dd.find('ul.dropdown > li');
	this.val = '';
	this.index = -1;
	this.initEvents();
}
DropDown.prototype = {
	initEvents : function() {
		var obj = this;

		obj.dd.on('click', function(event){
			$(this).toggleClass('active');
//			return false;
		});

		obj.opts.on('click',function(){
			var opt = $(this);
			obj.val = opt.text();
			obj.index = opt.index();
			obj.placeholder.text(obj.val);
		});
	},
	getValue : function() {
		return this.val;
	},
	getIndex : function() {
		return this.index;
	}
}

function fn_pagination_more(data, params) {
	var obj = $(params.obj);
	obj.remove();
	$.js_pinterest();
}

function fn_dialog(data, params) {
	
	if ( data.login_required ) {
		fn_login_form();
		return ;
	}
	
	var obj = $(params.obj);
	
	var opts = {
		buttons: false,
		width: obj.attr('data-width') || 620
	}

	if ( typeof(data.html) != 'undefined'&& typeof(data.html[params.result_ids]) != 'undefined' ) {
		var k = params.result_ids;

		cm_dialog_close_last();
		
		var html = '<div id="'+k+'">'+data.html[k]+'</div>';
		cm_dialog(obj.attr('data-title') || obj.attr('title') || obj.text(), html, opts)
		if (html != -1 || html.indexOf('<!--processForm') != -1) {
			jQuery.processForms($('#'+k).get());
		}
		
		var regex_all = new RegExp('<script[^>]*>([\u0001-\uFFFF]*?)</script>', 'img');
		var matches = [];
		
		matches = data.html[k].match(regex_all);
		
		if (matches) {

			var s_sources = [];
			jQuery.loaded_scripts = jQuery.loaded_scripts || [];

			for (var i = 0; i < matches.length; i++ ) {
				var m = $(matches[i]);

				if (m.attr('src')) {
					var _src = jQuery.getBaseName(m.attr('src'));
					var script_idx = jQuery.inArray(_src, jQuery.loaded_scripts);
					if (m.hasClass('cm-ajax-force') && script_idx != -1) {
						jQuery.loaded_scripts[script_idx] = null;
						script_idx = -1;
					}
					if (script_idx == -1) {
						s_sources.push(m.attr('src'));
					}
				} else {
					var _execute = false;
					if (!s_sources.length) {
						jQuery.globalEval(m.html());
					} else {
						_execute = true;
					}

					if (s_sources.length) {
						var list = [];
						for (var _i = 0; _i < s_sources.length ; _i++) {
							list.push($.getScript(s_sources[_i]));
						}

						if (_execute == true) {
							(function(s) {
								$.when.apply(null, list).then(function() {
									jQuery.globalEval(s);
								});
							})(m.html());
						}

						s_sources = [];
					}
				}
			}

			if (s_sources.length) {
				for (var _i = 0; _i < s_sources.length ; _i++) {
					$.getScript(s_sources[_i]);
				}
			}
		}
		
	}

}

function js_init_upload_avatar(el, upload_url, container) {
	var uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		file_data_name: 'avatar',
		browse_button : el,
		url : upload_url,
		unique_names : true,
		filters : {
			max_file_size : '4mb',
			mime_types: [
				{title : "Image files", extensions : "jpeg,jpg,gif,png"},
			]
		},
		flash_swf_url : '/themes/v2014/js/plupload/Moxie.swf',
		silverlight_xap_url : '/themes/v2014/js/plupload/Moxie.xap',

		init: {
			PostInit: function() {
			},

			FilesAdded: function(up, files) {
				up.start();
			},

			UploadProgress: function(up, file) {
				$(el).addClass('loading');
				$(container).addClass('loading');
			},
			
			FileUploaded: function(up, file, info) {
				$(el).removeClass('loading');
				$(container).removeClass('loading');
				var response = $.parseJSON(info.response);

				if ( response.data.uploadInfo.success ) {
					var uploadFile = response.data.uploadInfo.file;
					var api;
					var jcontainer = $(container).find('form');
					
					$('#preview img').attr('src', uploadFile.url);
					var img = $('<img src="'+uploadFile.url+'" alt="" />');
					jcontainer.html('');
					jcontainer.append(img);
					jcontainer.append('<input type="hidden" id="x" name="x" value="" />');
					jcontainer.append('<input type="hidden" id="y" name="y" value="" />');
					jcontainer.append('<input type="hidden" id="x2" name="x2" value="" />');
					jcontainer.append('<input type="hidden" id="y2" name="y2" value="" />');
					jcontainer.append('<input type="hidden" id="w" name="w" value="" />');
					jcontainer.append('<input type="hidden" id="h" name="h" value="" />');
					jcontainer.append('<input type="hidden" name="image_id" value="'+uploadFile.image_id+'" />');
					jcontainer.append('<input type="submit" name="choose_avatar" value="OK" />');
					
					var w = parseInt(uploadFile.width);
					var h = parseInt(uploadFile.height);
					var x = parseInt(uploadFile.width) / 2 - 100;
					var y = parseInt(uploadFile.height) / 2 - 100;
					
					function showPreview(coords) {
						var rx = 140 / coords.w;
						var ry = 140 / coords.h;

						$('#preview img').css({
							width: Math.round(rx * w) + 'px',
							height: Math.round(ry * h) + 'px',
							marginLeft: '-' + Math.round(rx * coords.x) + 'px',
							marginTop: '-' + Math.round(ry * coords.y) + 'px'
						});
						
						$('#x').val(parseInt(coords.x));
						$('#y').val(parseInt(coords.y));
						$('#x2').val(parseInt(coords.x2));
						$('#y2').val(parseInt(coords.y2));
						$('#w').val(parseInt(coords.w));
						$('#h').val(parseInt(coords.h));
					}
					
					img.Jcrop({
						allowSelect: false,
						onChange: showPreview,
						onSelect: showPreview,
						aspectRatio: 1,
						minSize: [200, 200],
						trueSize: [w, h],
						setSelect: [x, y, x + 200, y + 200],
						boxWidth: 440,
						boxHeight: 440
					}, function(){
						api = this;
//						api.ui.selection.addClass('jcrop-selection');
					});
				}
			},

			Error: function(up, err) {
				
				if ( err.code == -601 ) {
					err.message = 'Lỗi! Chỉ hỗ trợ PNG, JPG, JPEG, GIF.';
				}
				
				cm_notification({
					type: 'E',
					title: lang.error,
					message: err.message
				});
			}
		}
	});

	uploader.init();
}

function fn_like(data, params) {
	if ( data.login_required ) {
		fn_login_form();
		return ;
	}

	$(params.obj).find('> span').text(data.like);
	$(params.obj).find('> i').removeClass('icon-like icon-liked').addClass('icon-'+(data.liked ? 'liked' : 'like'));
}

function fn_friend(data, params) {
	
	if ( data && data.friend == 'ok' ) {
		$(params.obj).removeClass('cm-ajax').attr('href', '#').html(data.status);
	}
	
}

var dialog_stack = []
function cm_dialog_get_last() {
	if ( dialog_stack.length == 0 ) return $();

	//var dlg = dialog_stack[dialog_stack.length - 1];
	var dlg = dialog_stack.pop();

	return dlg;
}

function cm_dialog_close_last() {
	var dialog = cm_dialog_get_last();

	if ( dialog.dialog && dialog.dialog.length ) dialog.close();
}

function cm_dialog(title, message, opts) {
	var defaults = {
		title: title,
		modal: true,
		type: false
	}

	var settings = $.extend({}, defaults, opts);
	var html = '<div class="DialogWrap">'+message+'</div>';
	var dlg = new $.Dialog(html, settings);
	dialog_stack.push(dlg);
}

function cm_notification(notification) {
	var type;

	switch (notification.type) {
		case 'E':
			type = 'error';
			break;
		case 'W':
			type = 'warning';
			break;
		case 'N':
		default:
			type = 'information';
			break;
	}

	cm_dialog_close_last();
	cm_dialog(notification.title, notification.message, {
		type: type,
		width: 450
	});
}